#-*-coding:utf-8-*-
import sys
import os
import shutil
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from Widgets.progressBar_widget import *

class CopyThread(QThread):
    def __init__(self,originPath,desPath):
        super(CopyThread,self).__init__()
        self.origin_path=originPath
        self.des_path=desPath


    def run(self):
        shutil.copytree(self.origin_path,self.des_path)




class ProjectListWidget(QListWidget):

    def __init__(self):
        super(ProjectListWidget,self).__init__()

        #全局变量
        self.current_real_shot_path=''#当前镜头目录路径
        # self.current_real_sample_path=''#当前镜头对应的sample路径
        self.origin_dir_path=''
        self.origin_count=0 #拖入工程内文件夹/文件数量
        self.des_dir_path=''#project下的文件夹路径


        #双击事件
        self.doubleClicked.connect(self.__openFile)

        #添加右击菜单栏
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__rightMenu)

        #开启拖拽
        self.setAcceptDrops(True)#可被拖入
        # self.setDragEnabled(True)#自身可拖出

        self.mainList=[] #当前project下文件夹名称

        #计时器
        self.timer=QBasicTimer()

        #进度条
        self.p=MyProgressBar()

    def __rightMenu(self):
        self.menu=QMenu()
        self.openAction=QAction(u'打开目录',self)
        self.openAction.triggered.connect(self.__openDir)
        self.menu.addAction(self.openAction)

        self.menu.exec_(QCursor.pos())

    def dragEnterEvent(self, event):
        text=event.mimeData().text()
        dirPath=text[8:]#拖入的文件夹路径
        if dirPath.find('file:///')>=0:
            QMessageBox.information(self,'提示','请拖入单个文件夹')
        else:
            # text_list=text.split('\n')
            # # print(text_list)
            # dirPath_list=[x[8:] for x in text_list]#拖入的文件夹路径
            if self.current_real_shot_path=='':
                QMessageBox.information(self,'提示','请先选择具体镜头')
            else:
                project_path=os.path.join(self.current_real_shot_path,'project')
                if os.path.isdir(dirPath):#当拖入的是文件夹时
                    dirname = self.getFileNameByPath(dirPath)#当前拖入的文件夹名称
                    self.des_dir_path= os.path.join(project_path,dirname)#提交的项目目录

                    if dirname not in self.mainList:#当不重名时
                        filename_list=os.listdir(dirPath)#拖入文件夹下的所有文件/文件夹名称，这里要加入进度条
                        self.origin_count=len(filename_list)
                        self.p.show()
                        self.__threadOn(dirPath,self.des_dir_path)
                        self.mainList.append(dirname)
                        self.setList(self.mainList)
                    else:
                        reply=QMessageBox.question(self, '警告', '已存在该文件，是否覆盖？',QMessageBox.Yes|QMessageBox.No,QMessageBox.No)
                        if reply==QMessageBox.Yes:
                            print('YES')
                            # os.remove(sample_file_path)
                            # shutil.copyfile(filePath,sample_file_path)

                else:
                    QMessageBox.information(self,'提示','请拖入工程文件夹')



    def timerEvent(self, *args, **kwargs):
        if self.des_dir_path !='':
            if os.path.exists(self.des_dir_path):
                current_count=len(os.listdir(self.des_dir_path))
                delta=self.origin_count-current_count
                value=100-((delta)*100.0/self.origin_count)
                self.p.setValue(value)
                if value==100:
                    self.p.close()


    def __threadOn(self,originPath,desPath):
        self.timer.start(10,self)
        self.work=CopyThread(originPath,desPath)
        self.work.start()


    def getFileNameByPath(self,path):
        '''
        根据给的路径，返回文件路径
        :param path:
        :return:
        '''
        dirpath,name=os.path.split(path)
        return name

    def setList(self,namelist):
        '''
        设置整个显示列表内容
        :param namelist:
        :return:
        '''

        self.clear()
        self.mainList=namelist
        self.addItems(namelist)


    def addToList(self,name):
        '''
        将名称加入到self.mainList当中，然后更新
        :param name:
        :return:
        '''
        if name not in self.mainList:
            self.mainList.append(name)
            self.setList(self.mainList)

        else:
            QMessageBox.information(self,"提示","该文件已存在，请更新版本号再提交")



    def sendChooseName(self):
        current_item=self.currentItem()
        name=current_item.text()
        print(name)

    def __submitFilter(self,path):
        '''
        过滤函数，当选中的是文件夹还是单个文件
        :param path:
        :return:
        '''
        # filter_list=['.wmv','.asf','.asx','.rm','.rmvb','.mpg','.mpeg','.mpe','.3gp','.mov','.mp4','.m4v','.avi','.dat','.mkv','.flv','.vob',
        #              '.jpeg','.jpg','.png','.bmp','.gif','.psd','.pdd','.psdt','.tiff','.tiff']
        # fileType=os.path.splitext(path)[1]
        if os.path.isdir(path):
            return True
        else:
            return False


    def setCurrentShotPath(self,current_shot_path):
        '''
        设置当前镜头路径
        :param current_shot_path:
        :return:
        '''
        self.current_real_shot_path=current_shot_path



    def __openFile(self):
        '''
        双击就打开文件
        :return:
        '''
        filename=self.currentItem().text()
        file_path=os.path.join(self.current_real_shot_path,'project/%s'% filename)
        if file_path:
            os.startfile(file_path)

    def __openDir(self):
        '''
        打开当前目录
        :return:
        '''
        current_project_path=os.path.join(self.current_real_shot_path,'project')
        try:
            os.startfile(current_project_path)
        except:
            pass

if __name__ == '__main__':
    app=QApplication(sys.argv)
    F=ProjectListWidget()
    nameList=['a','b','c','d']
    F.setList(nameList)
    F.show()
    sys.exit(app.exec_())